package org.openkanban.server.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang.StringUtils;
import org.openkanban.server.domain.User;

/**
 * Util to get the Multipart File that is uploaded by an iFrame to save the
 * avatar image. A little bit *urrrghh* but DataSource-Binded file upload is
 * only enabled in commercial smartGWT EE.
 */
public class MultipartUtil {

    public static User processFiles(HttpServletRequest request, HttpServletResponse response) {
	SecureRandom random = new SecureRandom();
	String generatedFileName = new BigInteger(80, random).toString(32);
	return processFiles(generatedFileName, request, response);
    }

    /**
     * Searches the multipart file and creates it on the server.
     * 
     * @param targetFileName
     * @param request
     * @param response
     * @return
     */
    public static User processFiles(String targetFileName, HttpServletRequest request, HttpServletResponse response) {
	HashMap<String, String> args = new HashMap<String, String>();
	try {
	    ServletFileUpload upload = new ServletFileUpload();
	    FileItemIterator iter = upload.getItemIterator(request);
	    // pick up parameters first and note actual FileItem
	    while (iter.hasNext()) {
		FileItemStream item = iter.next();
		String name = item.getFieldName();
		if (item.isFormField()) {
		    args.put(name, Streams.asString(item.openStream()));
		} else {
		    args.put("contentType", item.getContentType());
		    String fileName = item.getName();
		    if (StringUtils.isNotBlank(fileName)) {

			int slash = fileName.lastIndexOf("/");
			if (slash < 0)
			    slash = fileName.lastIndexOf("\\");
			if (slash > 0)
			    fileName = fileName.substring(slash + 1);

			String[] fileNameArr = fileName.split("\\.");

			targetFileName += "." + fileNameArr[fileNameArr.length - 1];

			args.put("fileName", targetFileName);

			String contextName = args.get("context");
			if (contextName == null) {
			    contextName = request.getParameter("context");
			}
			InputStream in = null;
			try {
			    in = item.openStream();

			    File f = new File(request.getSession().getServletContext().getRealPath("") + "/images/avatar/"
				    + args.get("fileName").replaceAll("[.].*$", ""));

			    OutputStream out = new FileOutputStream(f);
			    byte buf[] = new byte[1024];
			    int len;
			    while ((len = in.read(buf)) > 0)
				out.write(buf, 0, len);
			    out.close();

			} catch (Exception e) {
			    e.printStackTrace();
			}
		    }
		}
	    }

	    User user = new User();

	    user.setVorname(args.get("vorname"));
	    user.setNachname(args.get("nachname"));
	    user.setEmail(args.get("email"));
	    user.setPassword(args.get("password"));
	    user.setNamensKuerzel(args.get("namensKuerzel"));

	    if (args.containsKey("fileName")) {
		user.setAvatarUrl(args.get("fileName").replaceAll("[.].*$", ""));
	    }

	    return user;

	} catch (Exception e) {
	    System.out.println(e.getMessage());
	}

	return null;
    }
}
